//
//  ViewController.m
//  AttendenceSys
//
//  Created by 窦芳俊 on 16/1/12.
//  Copyright © 2016年 窦芳俊. All rights reserved.
//

#import "ASLoginViewController.h"
#import "ASAppDelegate.h"
#import "ASNetworkEngine.h"
#import "API.h"
#import "ASLoginUserInfo.h"
#import "NSDictionary+Utils.h"
#import "SVProgressHUD.h"
#import "FileUtil.h"
#import "ASPracUnitLoginUserInfo.h"

@interface ASLoginViewController ()

@property (nonatomic, strong) ASLoginUserInfo* loginUserInfo;
@property (nonatomic, strong) ASPracUnitLoginUserInfo *pracUnitUserInfo;

@end

@implementation ASLoginViewController

- (void)dealloc
{
    _stuBtn = nil;
    _teaBtn = nil;
    _loginBtn = nil;
    _forgotPwdBtn = nil;
    _userField = nil;
    _passwordField = nil;
    _userLab = nil;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initView];
    [self initData];
}

// 初始化登陆View
- (void)initView
{
    _loginImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    _loginImageView.backgroundColor = [UIColor whiteColor];
    _loginImageView.userInteractionEnabled = YES;
    _loginImageView.image = [UIImage imageNamed:@"login_bg"];
    [self.view addSubview:_loginImageView];
    
    // 学生出勤管理系统
    UILabel* stuManageSyslab = [[UILabel alloc] initWithFrame:CGRectMake(0, 90, self.view.frame.size.width,30)];
    [stuManageSyslab setBackgroundColor:[UIColor clearColor]];
    [stuManageSyslab setText:@"南师法苑"];
    [stuManageSyslab setTextColor:[UIColor blackColor]];
    [stuManageSyslab setTextAlignment:NSTextAlignmentCenter];
    stuManageSyslab.font = [UIFont fontWithName:@"Arial" size:18.0];
    [_loginImageView addSubview:stuManageSyslab];
    
    // 学生
     _stuBtn = [[UIButton alloc] initWithFrame:CGRectMake(0,
                                                          stuManageSyslab.frame.origin.y+stuManageSyslab.frame.size.height+50,
                                                          self.view.frame.size.width/3,
                                                          60)];
    [_stuBtn setBackgroundImage:[UIImage imageNamed:@"bg_student_activited"] forState:UIControlStateNormal];
    [_stuBtn setTitle:@"学生" forState:UIControlStateNormal];
    [_stuBtn addTarget:self action:@selector(selectStuOrTeacherOrPracUnit:) forControlEvents:UIControlEventTouchUpInside];
    _stuBtn.tag = 100;
    [_stuBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _stuBtn.backgroundColor = [UIColor clearColor];
    [_loginImageView addSubview:_stuBtn];
    
    // 老师
    _teaBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width/3,
                                                         _stuBtn.frame.origin.y,
                                                         self.view.frame.size.width/3,
                                                         60)];
    [_teaBtn setTitle:@"老师" forState:UIControlStateNormal];
    [_teaBtn addTarget:self action:@selector(selectStuOrTeacherOrPracUnit:) forControlEvents:UIControlEventTouchUpInside];
    _teaBtn.tag = 200;
    [_teaBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _teaBtn.backgroundColor = [UIColor whiteColor];
    [_loginImageView addSubview:_teaBtn];
    
    // 在老师按钮左右两侧增加分割线
    UIImageView *leftSeparateLine = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width/3,
                                                                                  _stuBtn.frame.origin.y,
                                                                                  1,
                                                                                  60)];
    [leftSeparateLine setBackgroundColor:RGB(255.0, 240.0, 233.0)];
    [_loginImageView addSubview:leftSeparateLine];
    
    UIImageView *rightSeparateLine = [[UIImageView alloc] initWithFrame:CGRectMake(2*self.view.frame.size.width/3-1,
                                                                                  _stuBtn.frame.origin.y,
                                                                                  1,
                                                                                  60)];
    [rightSeparateLine setBackgroundColor:RGB(255.0, 240.0, 233.0)];
    [_loginImageView addSubview:rightSeparateLine];
    
    // 实习单位
    _practiceUnitBtn = [[UIButton alloc] initWithFrame:CGRectMake(2*self.view.frame.size.width/3,
                                                                  _stuBtn.frame.origin.y,
                                                                  self.view.frame.size.width/3,
                                                                  60)];
    [_practiceUnitBtn setTitle:@"实习单位" forState:UIControlStateNormal];
    [_practiceUnitBtn addTarget:self action:@selector(selectStuOrTeacherOrPracUnit:) forControlEvents:UIControlEventTouchUpInside];
    _practiceUnitBtn.tag = 300;
    [_practiceUnitBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _practiceUnitBtn.backgroundColor = [UIColor whiteColor];
    [_loginImageView addSubview:_practiceUnitBtn];
    
    // 用户名
    UIView* userView = [[UIView alloc] initWithFrame:CGRectMake(0,
                                                                _stuBtn.frame.origin.y+_stuBtn.frame.size.height,
                                                                self.view.frame.size.width,
                                                                _stuBtn.frame.size.height+10)];
    UIImageView* userimgView = [[UIImageView alloc] initWithFrame:CGRectMake(20, (userView.frame.size.height-19.5)/2, 20.5, 19.5)];
    userView.backgroundColor = [UIColor clearColor];
    [userimgView setImage:[UIImage imageNamed:@"ic_phone"]];
    [userView addSubview:userimgView];
    
    _userLab = [[UILabel alloc] initWithFrame:CGRectMake(userimgView.frame.size.width+20*2, userimgView.frame.origin.y+2, 60, 17)];
    [_userLab setFont:[UIFont fontWithName:@"Arial" size:18.0]];
    [_userLab setText:@"学号"];
    [_userLab setTextColor:[UIColor blackColor]];
    _userLab.textAlignment = NSTextAlignmentLeft;
    [userView addSubview:_userLab];
    
    _userField = [[UITextField alloc] initWithFrame:CGRectMake(_userLab.frame.origin.x+_userLab.frame.size.width+2,
                                                               _userLab.frame.origin.y,
                                                               self.view.frame.size.width-(_userLab.frame.origin.x+_userLab.frame.size.width+2)-20,
                                                               20)];
    _userField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _userField.textColor = [UIColor blackColor];
    _userField.returnKeyType = UIReturnKeyDone;
    _userField.placeholder = @"请输入学号";
    [_userField setBackgroundColor:[UIColor clearColor]];
    _userField.delegate = self;
    _userField.font = [UIFont systemFontOfSize:18.0f];
    _userField.borderStyle = UITextBorderStyleNone;
    [userView addSubview:_userField];
    [_loginImageView addSubview:userView];
    
    // 间隔线
    UIImageView* lineView = [[UIImageView alloc] initWithFrame:CGRectMake(0,
                                                                          userView.frame.origin.y+userView.frame.size.height+1,
                                                                          self.view.frame.size.width,
                                                                          1)];
    [lineView setBackgroundColor:RGB(221.0, 221.0, 221.0)];
    [_loginImageView addSubview:lineView];
    
    // 密码
    UIView* pwdView = [[UIView alloc] initWithFrame:CGRectMake(0, userView.frame.origin.y+userView.frame.size.height, self.view.frame.size.width, userView.frame.size.height)];
    UIImageView* pwdimgView = [[UIImageView alloc] initWithFrame:CGRectMake(20, (userView.frame.size.height-17.5)/2, 17.5, 17.5)];
    pwdView.backgroundColor = [UIColor clearColor];
    [pwdimgView setImage:[UIImage imageNamed:@"ic_password"]];
    [pwdView addSubview:pwdimgView];
    
    UILabel* pwdLab = [[UILabel alloc] initWithFrame:CGRectMake(_userLab.frame.origin.x, pwdimgView.frame.origin.y+2, 60, 17)];
    [pwdLab setFont:[UIFont fontWithName:@"Arial" size:18.0]];
    [pwdLab setTextColor:[UIColor blackColor]];
    [pwdLab setText:@"密码"];
    pwdLab.textAlignment = NSTextAlignmentLeft;
    [pwdView addSubview:pwdLab];
    
    _passwordField = [[UITextField alloc] initWithFrame:CGRectMake(pwdLab.frame.origin.x+pwdLab.frame.size.width+2, pwdLab.frame.origin.y,self.view.frame.size.width-(pwdLab.frame.origin.x+pwdLab.frame.size.width+2)-20, 20)];
    _passwordField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _passwordField.textColor = [UIColor blackColor];
    _passwordField.returnKeyType = UIReturnKeyDone;
    [_passwordField setBackgroundColor:[UIColor clearColor]];
    _passwordField.placeholder = @"请输入密码";
    _passwordField.delegate = self;
    _passwordField.font = [UIFont systemFontOfSize:18.0f];
    _passwordField.borderStyle = UITextBorderStyleNone;
    _passwordField.secureTextEntry = YES;
    [pwdView addSubview:_passwordField];
    [_loginImageView addSubview:pwdView];
    
    // 登陆 忘记密码
    _loginBtn = [[UIButton alloc] initWithFrame:CGRectMake(_userLab.frame.origin.x, pwdView.frame.origin.y+pwdView.frame.size.height+40, self.view.frame.size.width-2*_userLab.frame.origin.x, 50)];
    [_loginBtn setTitle:@"马上登录" forState:UIControlStateNormal];
    [_loginBtn addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    [_loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _loginBtn.backgroundColor = RGB(252, 119, 62);
    [_loginImageView addSubview:_loginBtn];
    
    _forgotPwdBtn = [[UIButton alloc] initWithFrame:CGRectMake((self.view.frame.size.width-100)/2,
                                                               _loginBtn.frame.origin.y+_loginBtn.frame.size.height+25,
                                                               100,
                                                               30)];
    [_forgotPwdBtn setTitle:@"忘记密码？" forState:UIControlStateNormal];
    [_forgotPwdBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_forgotPwdBtn addTarget:self action:@selector(forgetpwd) forControlEvents:UIControlEventTouchUpInside];
    _forgotPwdBtn.backgroundColor = [UIColor clearColor];
    //[_loginImageView addSubview:_forgotPwdBtn];
}

- (void)initData
{
    _bSelStatus = 0;//默认选中学生
}

- (void)selectStuOrTeacherOrPracUnit:(id)sender
{
    UIButton* btn = (UIButton*)sender;
 
    if (100 == btn.tag)
    {
        // 点击学生
        [_userLab setText:@"学号"];
        _userField.placeholder = @"请输入学号";
        
        if (0 == _bSelStatus)
        {
            return;
        }
        _bSelStatus = 0;
        
        _stuBtn.enabled = NO;
        _teaBtn.enabled = YES;
        _practiceUnitBtn.enabled = YES;
        
        [_stuBtn setBackgroundImage:[UIImage imageNamed:@"bg_student_activited"] forState:UIControlStateNormal];
        [_stuBtn setBackgroundColor:[UIColor clearColor]];
        [_teaBtn setBackgroundColor:[UIColor whiteColor]];
        [_teaBtn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        [_practiceUnitBtn setBackgroundColor:[UIColor whiteColor]];
        [_practiceUnitBtn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    }
    else if (200 == btn.tag)
    {
        // 点击老师
        [_userLab setText:@"工号"];
        _userField.placeholder = @"请输入工号";
        
        if (1 == _bSelStatus)
        {
            return;
        }
        _bSelStatus = 1;
        
        _teaBtn.enabled = NO;
        _stuBtn.enabled = YES;
        _practiceUnitBtn.enabled = YES;
        
        [_teaBtn setBackgroundImage:[UIImage imageNamed:@"bg_student_activited"] forState:UIControlStateNormal];
        [_teaBtn setBackgroundColor:[UIColor clearColor]];
        [_stuBtn setBackgroundColor:[UIColor whiteColor]];
        [_stuBtn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        [_practiceUnitBtn setBackgroundColor:[UIColor whiteColor]];
        [_practiceUnitBtn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    }
    else if (300 == btn.tag)
    {
        // 点击实习单位
        [_userLab setText:@"帐号"];
        _userField.placeholder = @"请输入帐号";
        if (2 == _bSelStatus)
        {
            return;
        }
        _bSelStatus = 2;
        
        _teaBtn.enabled = YES;
        _stuBtn.enabled = YES;
        _practiceUnitBtn.enabled = NO;
        
        [_practiceUnitBtn setBackgroundImage:[UIImage imageNamed:@"bg_student_activited"] forState:UIControlStateNormal];
        [_practiceUnitBtn setBackgroundColor:[UIColor clearColor]];
        [_teaBtn setBackgroundColor:[UIColor whiteColor]];
        [_teaBtn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        [_stuBtn setBackgroundColor:[UIColor whiteColor]];
        [_stuBtn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    }
}

/**
 * 实习单位登陆
 */
- (void)practiceUnitLogin
{
    //登录接口 http://211.65.216.54//mobileLogin.action?userCode=2code&passWord=888888&sourceTypeId=3
    //单位账户登录的接口 sourceTypeId=3 写死。 userCode是单位账户编号  passWord单位账户密码，这个登录的密码 不用MD5加密。 安全性低
    
    NSString* userAccount = _userField.text;
    NSString* psd = _passwordField.text;
    NSString* refer = @"/mobileLogin.action?";
    NSString* prefix = kASHttpUrl(refer);

    NSString* totalUrl = [NSString stringWithFormat:@"%@userCode=%@&passWord=%@&sourceTypeId=3", prefix, userAccount, psd];
    
    [SVProgressHUD showWithStatus:@"登录中..." maskType:SVProgressHUDMaskTypeClear];
    ASNetworkEngine *networkingEngine = [ASNetworkEngine sharedInstance];
    [networkingEngine GET:totalUrl parameters:nil success:^(id responseObject) {
        NSDictionary* jsonRsp = (NSDictionary *)responseObject;
        if (isSuccessRsp(jsonRsp))
        {
            NSDictionary* data = [jsonRsp objectForKey:kASAccountJsonData];
            data = [data processDictionaryIsNSNull:data];
        
            _pracUnitUserInfo = [[ASPracUnitLoginUserInfo alloc] init];
            [self parsePracUnitLoginUserInfo:_pracUnitUserInfo data:data];
            
            AS_APP_UserType = _bSelStatus;
            [SVProgressHUD dismiss];
            
            [[ASAppDelegate sharedAppDelegate] savePracUnitLoginUserInfo:_pracUnitUserInfo];
            [[ASAppDelegate sharedAppDelegate] enterMainView];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:errorMsgRsp(jsonRsp)];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络异常，请稍后再试"];
    }];
}

// 登陆
- (void)login
{
    if (2 == _bSelStatus)
    {
        //实习单位登陆
        [self practiceUnitLogin];
        return;
    }
    
    //登录接口：http://121.42.185.124:8080/LawSchool/mobileLogin.action?userCode=xiaohu&passWord=21218cca77804d2ba1922c33e0151105&sourceTypeId=3
    //userCode学号   passWord密码（MD5加密） sourceTypeId  1 老师  2 学生 3管理员

    // 获取输入的学号/工号、密码
    NSString* userAcnt = _userField.text;
    NSString* psd = _passwordField.text;
    NSString* psdMd5 = stringToMd5(psd);
    NSString* refer = @"/mobileLogin.action?";
    NSString* prefix = kASHttpUrl(refer);
    NSString* sourceType = @"2";
    if (1 == _bSelStatus)
    {
        sourceType = @"1";
    }
    NSString* totalUrl = [NSString stringWithFormat:@"%@userCode=%@&passWord=%@&sourceTypeId=%@", prefix, userAcnt, psdMd5, sourceType];
    
    [SVProgressHUD showWithStatus:@"登录中..." maskType:SVProgressHUDMaskTypeClear];
    ASNetworkEngine *networkingEngine = [ASNetworkEngine sharedInstance];
    [networkingEngine GET:totalUrl parameters:nil success:^(id responseObject) {
        NSDictionary* jsonRsp = (NSDictionary *)responseObject;
        if (isSuccessRsp(jsonRsp))
        {
            NSDictionary* data = [jsonRsp objectForKey:kASJsonData];
            data = [data processDictionaryIsNSNull:data];
            _loginUserInfo = [[ASLoginUserInfo alloc] init];
            [self parseLoginUserInfo:_loginUserInfo data:data];
            
            //AS_APP_UserTypeStu = _bSeleStu;
            AS_APP_UserType = _bSelStatus;
            [SVProgressHUD dismiss];
            [[ASAppDelegate sharedAppDelegate] saveLoginUserInfo:_loginUserInfo];
            [[ASAppDelegate sharedAppDelegate] enterMainView];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:errorMsgRsp(jsonRsp)];
        }
    } failure:^(NSError *error) {
        //[SVProgressHUD showErrorWithStatus:error.description];
        [SVProgressHUD showErrorWithStatus:@"网络异常，请稍后再试"];
    }];
}

- (void)parseLoginUserInfo:(ASLoginUserInfo*)info data:(NSDictionary*)dataDic
{
    info.age = [dataDic objectForKey:@"age"];
    info.className = [dataDic objectForKey:@"className"];
    info.classId = [dataDic objectForKey:@"classId"];
    info.collegeName = [dataDic objectForKey:@"collegeName"];
    info.majorName = [dataDic objectForKey:@"majorName"];
    info.portraitNum = [dataDic objectForKey:@"portraitNum"];
    info.sex = [dataDic objectForKey:@"sex"];
    info.sourceSecTypeId = [dataDic objectForKey:@"sourceSecTypeId"];
    info.sourceSecTypeName = [dataDic objectForKey:@"sourceSecTypeName"];
    info.sourceTypeId = [dataDic objectForKey:@"sourceTypeId"];
    info.sourceTypeName = [dataDic objectForKey:@"sourceTypeName"];
    info.userBirth = [dataDic objectForKey:@"userBirth"];
    info.userCode = [dataDic objectForKey:@"userCode"];
    info.userEmail = [dataDic objectForKey:@"userEmail"];
    info.userId = [dataDic objectForKey:@"userId"];
    info.userMobile = [dataDic objectForKey:@"userMobile"];
    info.userName = [dataDic objectForKey:@"userName"];
    info.userPic = [dataDic objectForKey:@"userPic"];
    info.dormitory = [dataDic objectForKey:@"dormitory"];
    info.political = [dataDic objectForKey:@"political"];
    
    //此处增加判断头像是否有更新，如果有则下载至本地
//    NSString *userPicName = [self fetchUserPicName:info.userPic];
//    
//    if (userPicName != nil)
//    {
//        if (![self judgeUserPicFileExist:userPicName])
//        {
//            //不存在本地 则下载
//            ASNetworkEngine *netEngine = [ASNetworkEngine sharedInstance];
//            [netEngine downloadWithUrl:info.userPic savePath:[self fetchUserPicFilePath:userPicName] progressBlock:^(long long bytesRead, long long totalBytes) {
//                
//            } completionBlock:^(id responseObject) {
//                NSLog(@"xia zai");
//            } failure:^(NSString *errorMsg) {
//                
//            }];
//        }
//    }
}

- (void)parsePracUnitLoginUserInfo:(ASPracUnitLoginUserInfo*)info data:(NSDictionary*)dataDic
{
    info.accountAddress = [dataDic objectForKey:@"accountAddress"];
    info.accountCode = [dataDic objectForKey:@"accountCode"];
    info.accountName = [dataDic objectForKey:@"accountName"];
    info.accountPassword = [dataDic objectForKey:@"accountPassword"];
    info.accountProperty = [dataDic objectForKey:@"accountProperty"];
    info.pkAccountId = [dataDic objectForKey:@"pkAccountId"];
}

- (NSString*)fetchUserPicName:(NSString*)url
{
    NSString *tmp = [url copy];
    NSRange range = [tmp rangeOfString:@"/" options:NSBackwardsSearch];
    
    if (range.location == NSNotFound)
    {
        return nil;
    }
    
    return [tmp substringFromIndex:range.location];
}

- (NSString*)fetchUserPicFilePath:(NSString*)picName
{
    NSString* path = [kFileUtil getAppDataPath];
    path = [path stringByAppendingPathComponent:@"Pic"];
    
    if (![kFileUtil isFileExist:path])
    {
        [kFileUtil createPath:path];
    }
    
    path = [path stringByAppendingPathComponent:picName];
    
    return path;
}

- (BOOL)judgeUserPicFileExist:(NSString*)picName
{
    NSString* path = [kFileUtil getAppDataPath];
    path = [path stringByAppendingPathComponent:@"Pic"];
    path = [path stringByAppendingPathComponent:picName];
    
    return [kFileUtil isFileExist:path];
}

// 忘记密码
- (void)forgetpwd
{
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (self.passwordField == textField) {
        _loginImageView.frame = CGRectMake(0, -50, self.view.frame.size.width, self.view.frame.size.height);
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField;
{
    [textField resignFirstResponder];
    _loginImageView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    if (self.passwordField == textField) {
        [self login];
    }
    return YES;
}

@end
